// 转日期时间戳到微信日期字符串 2021-01-01+10:10:10 / 2021-01-01 10:10:10 --> 20210101101010
function formatDateWithTimeZone (timestamp, timeZone = 'Asia/Shanghai') {
  const offset = getTimezoneOffset(timeZone)

  // 将时区偏移加到时间戳上
  const adjustedTimestamp = timestamp + offset * 60 * 1000

  const adjustedDate = new Date(adjustedTimestamp)

  const year = adjustedDate.getUTCFullYear()
  const month = (adjustedDate.getUTCMonth() + 1).toString().padStart(2, '0')
  const day = adjustedDate.getUTCDate().toString().padStart(2, '0')
  const hours = adjustedDate.getUTCHours().toString().padStart(2, '0')
  const minutes = adjustedDate.getUTCMinutes().toString().padStart(2, '0')
  const seconds = adjustedDate.getUTCSeconds().toString().padStart(2, '0')

  const formattedDate = `${year}${month}${day}${hours}${minutes}${seconds}`

  return formattedDate
}

// 获取时区偏移
function getTimezoneOffset (timeZone) {
  const offsetInMinutes = new Date().getTimezoneOffset()
  const offset = timeZone === 'UTC' ? 0 : -offsetInMinutes
  return offset
}

// 将对象内属性名首个字母变成小写
function convertObjectKeysToLowercase (obj) {
  const convertedObject = {}

  Object.keys(obj).forEach(key => {
    const lowercasedKey = key.charAt(0).toLowerCase() + key.slice(1)
    convertedObject[lowercasedKey] = obj[key]
  })

  return convertedObject
}

export default {
  getOrderInfo: {
    args: {
      _purify: {
        // subject在使用支付宝时必传，在微信支付这里特殊处理一下，直接删除
        shouldDelete: ['subject', 'tradeType']
      }
    }
  },
  orderQuery: {
    args: {
      orderId: 'outTradeNo',
      wxOrderId: 'transactionId'
    },
    returnValue: {
      _pre (args) {
        const originalResult = JSON.parse(JSON.stringify(args.order))
        let tradeState = ''
        let tradeStateDesc = ''
        // status 当前状态 0-订单初始化（未创建成功，不可用于支付）1-订单创建成功 2-订单已经支付，待发货 3-订单发货中 4-订单已发货 5-订单已经退款 6-订单已经关闭（不可再使用） 7-订单退款失败 8-用户退款完成 9-回收广告金完成 10-分账回退完成
        if ([0, 1].indexOf(originalResult.status) > -1) {
          tradeState = 'NOTPAY'
          tradeStateDesc = '未支付'
        } else if ([6].indexOf(originalResult.status) > -1) {
          tradeState = 'PAYERROR'
          tradeStateDesc = '支付失败'
        } else if ([2, 3, 4].indexOf(originalResult.status) > -1) {
          tradeState = 'SUCCESS'
          tradeStateDesc = '支付成功'
        } else if ([5, 8, 9, 10].indexOf(originalResult.status) > -1) {
          tradeState = 'REFUND'
          tradeStateDesc = '订单发生过退款'
        } else if ([7].indexOf(originalResult.status) > -1) {
          tradeState = 'REFUNDRROR'
          tradeStateDesc = '订单退款失败'
        } else {
          tradeState = 'NOTPAY'
          tradeStateDesc = '未支付'
        }
        let res = {
          outTradeNo: originalResult.order_id,
          transactionId: originalResult.wx_order_id,
          totalFee: originalResult.order_fee,
          cashFee: originalResult.paid_fee,
          leftFee: originalResult.left_fee,
          couponFee: originalResult.coupon_fee,
          tradeState,
          tradeStateDesc,
          refundFee: originalResult.refund_fee,
          originalResult
        }
        res = JSON.parse(JSON.stringify(res))
        return res
      }
    }
  },

  refund: {
    args: {
      _purify: {
        shouldDelete: ['totalFee', 'refundFeeType', 'refundDesc']
      },
      orderId: 'outTradeNo',
      wxOrderId: 'transactionId',
      refundOrderId: 'outRefundNo',
      refundFee: 'refundFee'
    },
    returnValue: {
      // refundFee: 'amount.refund',
      // cashRefundFee: 'amount.payer_refund'
    }
  },
  refundQuery: {
    args: {
      orderId: 'outRefundNo',
      wxOrderId: 'transactionId'
    },
    returnValue: {
      _pre (args) {
        const originalResult = JSON.parse(JSON.stringify(args.order))
        let tradeState = ''
        let tradeStateDesc = ''
        // status 当前状态 0-订单初始化（未创建成功，不可用于支付）1-订单创建成功 2-订单已经支付，待发货 3-订单发货中 4-订单已发货 5-订单已经退款 6-订单已经关闭（不可再使用） 7-订单退款失败 8-用户退款完成 9-回收广告金完成 10-分账回退完成
        if ([0, 1].indexOf(originalResult.status) > -1) {
          tradeState = 'NOTPAY'
          tradeStateDesc = '未支付'
        } else if ([6].indexOf(originalResult.status) > -1) {
          tradeState = 'PAYERROR'
          tradeStateDesc = '支付失败'
        } else if ([2, 3, 4].indexOf(originalResult.status) > -1) {
          tradeState = 'SUCCESS'
          tradeStateDesc = '支付成功'
        } else if ([5, 8, 9, 10].indexOf(originalResult.status) > -1) {
          tradeState = 'REFUND'
          tradeStateDesc = '订单发生过退款'
        } else if ([7].indexOf(originalResult.status) > -1) {
          tradeState = 'REFUNDRROR'
          tradeStateDesc = '订单退款失败'
        } else {
          tradeState = 'NOTPAY'
          tradeStateDesc = '未支付'
        }
        let res = {
          outTradeNo: originalResult.order_id,
          transactionId: originalResult.wx_order_id,
          totalFee: originalResult.order_fee,
          cashFee: originalResult.paid_fee,
          couponFee: originalResult.coupon_fee,
          tradeState,
          tradeStateDesc,
          refundFee: originalResult.refund_fee,
          originalResult
        }
        res = JSON.parse(JSON.stringify(res))
        return res
      }
    }
  },
  verifyPaymentNotify: {
    returnValue: {
      _pre (args) {
        const outTradeNo = args.OutTradeNo
        const timeEnd = args.WeChatPayInfo ? args.WeChatPayInfo.PaidTime * 1000 : Date.now()
        const transactionId = args.WeChatPayInfo ? args.WeChatPayInfo.MchOrderNo : undefined
        const openid = args.OpenId
        const appId = args.appId
        const env = args.Env
        if (args.Event === 'xpay_goods_deliver_notify') {
          // 道具直购
          return {
            outTradeNo,
            transactionId,
            tradeState: 'SUCCESS',
            openid,
            appId,
            totalFee: args.GoodsInfo.Quantity * args.GoodsInfo.OrigPrice,
            cashFee: args.GoodsInfo.Quantity * args.GoodsInfo.ActualPrice,
            attach: args.GoodsInfo.Attach,
            timeEnd: formatDateWithTimeZone(timeEnd),
            goodsInfo: convertObjectKeysToLowercase(args.GoodsInfo),
            weChatPayInfo: convertObjectKeysToLowercase(args.WeChatPayInfo),
            env
          }
        } else if (args.Event === 'xpay_coin_pay_notify') {
          // 购买代币
          return {
            outTradeNo,
            transactionId,
            tradeState: 'SUCCESS',
            openid,
            appId,
            totalFee: args.CoinInfo.Quantity * args.CoinInfo.OrigPrice,
            cashFee: args.CoinInfo.Quantity * args.CoinInfo.ActualPrice,
            attach: args.CoinInfo.Attach,
            timeEnd: formatDateWithTimeZone(timeEnd),
            coinInfo: convertObjectKeysToLowercase(args.CoinInfo),
            weChatPayInfo: convertObjectKeysToLowercase(args.WeChatPayInfo),
            env
          }
        }
      }
    }
  },
  verifyRefundNotify: {
    returnValue: {
      _pre (args) {
        const outTradeNo = args.MchOrderId
        const transactionId = args.WxpayRefundTransactionId
        const openid = args.OpenId
        const appId = args.appId
        // 退款通知
        return {
          outTradeNo,
          transactionId,
          openid,
          appId,
          refundFee: args.RefundFee,
          outRefundNo: args.MchRefundId,
          refundStatus: args.RetCode === 0 ? 'SUCCESS' : 'CHANGE',
          retMsg: args.RetMsg,
          retryCount: args.RetryTimes
        }
      }
    }
  },
  notifyProvideGoods: {
    args: {
      orderId: 'outTradeNo',
      wxOrderId: 'transactionId'
    },
    returnValue: {

    }
  },
  currencyPay: {
    args: {
      orderId: 'outTradeNo'
    },
    returnValue: {
      outTradeNo: 'orderId'
    }
  },
  cancelCurrencyPay: {
    args: {
      payOrderId: 'outTradeNo',
      orderId: 'outRefundNo'
    },
    returnValue: {
      outRefundNo: 'orderId'
    }
  },
  presentCurrency: {
    args: {
      orderId: 'outTradeNo'
    },
    returnValue: {
      outTradeNo: 'orderId'
    }
  }
}
